package operator

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/md5"
	"project/pkg/mildware"
	"project/pkg/models"
	"project/pkg/validate"
)

func (h OHandler) UpdateInfo(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.UpdateInfo)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Op:UpdateInfo with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Op:UpdateInfo with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//token
	ID, _, name, err := mildware.GetCyrrentUserID(c)
	if err != nil {
		zap.L().Error("Op:UpdateInfo mildware.GetCyrrentUserID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	//更新
	//判断这个学生是否提交过
	exits, info, err := h.M.OpCheckExistByUsername(req.Username)
	if !exits {
		resp.SendCode(c, models.CodeUserNotExist)
		return
	}
	//则这次是更新操作
	info.CreateName = name
	info.CreateId = ID
	info.StudentName = req.StudentName
	info.Password = md5.MD5(req.Password)
	err = h.M.OpUpdateInfoBuID(info)
	if err != nil {
		zap.L().Error("Op:UpdateInfo h.M.OpUpdateInfoBuID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
	return
}
